// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-20 13:37
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.ArraysTrain;

import java.util.ArrayList;
import java.util.List;

public class ThreeSumClosest {
    List<Integer> t = new ArrayList<>();

    /**
     * 最接近的三数之和 -> 二进制枚举 -> 当数组长度大于32位的时候会导致数据溢出
     *
     * @param nums
     * @param target
     * @return
     */
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length, diff = Integer.MAX_VALUE, res = 0;
        for (int i = 0; i < (1 << n); i++) {
            if (Integer.bitCount(i) == 3) {
                int sum = 0;
                t.clear();
                for (int j = 0; j < n; j++) {
                    if (((i >> j) & 1) == 1) {
                        sum += nums[j];
                        t.add(nums[j]);
                    }
                }
                if (diff > (Math.abs(sum - target))) {
                    res = sum;
                    diff = Math.abs(sum - target);
                    if (diff == 0) {
                        System.out.println("diff =" + diff);
                        System.out.println(t);
                        System.out.println(Integer.toBinaryString(i));
                    }
                }
            }
        }
        return res;
    }
}
